package com.lwj.project1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.lwj.project1.databaseHelper.ImageUtil;
import com.lwj.project1.databaseHelper.MySqliteOpenHelper;
import com.lwj.project1.entity.GameCategory;
import com.lwj.project1.entity.Model;
import com.lwj.project1.myToast.MyToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class AddCategoryActivity extends AppCompatActivity {

    private ImageButton gameCategoryImg;
    private EditText gameCategoryName;
    private EditText gameCategoryModel;
    private EditText gameCategoryDescription;
    private MySqliteOpenHelper mySqliteOpenHelper;
    private MyToast myToast;
    private String gameImgStr;
    private Button submit;
    private Button refresh;
    private Button delete;
    Model addModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_category);

        gameCategoryImg = findViewById(R.id.addCategoryImg);
        gameCategoryName = findViewById(R.id.addCategoryName);
        gameCategoryModel = findViewById(R.id.addCategoryModel);
        gameCategoryDescription = findViewById(R.id.addCategoryDescription);
        submit = findViewById(R.id.button3);
        refresh = findViewById(R.id.button5);
        delete = findViewById(R.id.button7);

        myToast = new MyToast(getApplicationContext());
        mySqliteOpenHelper = new MySqliteOpenHelper(getApplicationContext());


        gameCategoryImg.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(AddCategoryActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                getFromAlbum();
            }else{
                ActivityCompat.requestPermissions(AddCategoryActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
            }
        });

        // TODO 需要对于Model进行检查 或者换一个控件进行输入
        submit.setOnClickListener(v -> {
            if (gameImgStr == null){
                myToast.showToastWithImg("你还没有上传桌游图片哦~",getResources().getDrawable(R.drawable.toast_img));
                return;
            }
            String name = gameCategoryName.getText().toString();
            String model = gameCategoryModel.getText().toString();
            System.out.println(model);
            String description = gameCategoryDescription.getText().toString();
            switch (model){
                case "AMERICAN":
                    addModel = Model.AMERICAN;break;
                case "GERMANY":
                    addModel = Model.GERMANY;break;
                case "TRPG":
                    addModel = Model.TRPG;break;
                case "PARTY":
                    addModel = Model.PARTY;break;
                case "TRADITION":
                    addModel = Model.TRADITION;break;
                case "WAR":
                    addModel = Model.WAR;break;
                default:{
                    myToast.showToastWithImg("桌游模式不对哦~检查一下吧~",getResources().getDrawable(R.drawable.toast_img));
                    return;
                }
            }
            if (!mySqliteOpenHelper.addGameCategory(new GameCategory(name,gameImgStr,description,addModel))){
                myToast.showToastWithImg("添加失败了哦，是不是已经添加过啦？",getResources().getDrawable(R.drawable.toast_img));
            }else myToast.showToastWithImg("添加成功啦~",getResources().getDrawable(R.drawable.toast_img));
        });
        refresh.setOnClickListener(v -> {
            gameCategoryDescription.setText("");
            gameCategoryName.setText("");
            gameCategoryModel.setText("");
            gameCategoryImg.setImageResource(R.drawable.game);
        });
        delete.setOnClickListener(v -> {
            if (mySqliteOpenHelper.deleteGameCategoryByName(gameCategoryName.getText().toString())){
                myToast.showToastWithImg("删除成功啦~",getResources().getDrawable(R.drawable.toast_img));
            }else myToast.showToastWithImg("删除失败啦~是不是名字错了呢~",getResources().getDrawable(R.drawable.toast_img));
        });
    }

    
    private void getFromAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,1);
    }
    public void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1){
            handleImage(data);
        }
    }

    private void handleImage(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(AddCategoryActivity.this,uri)){
            String documentId = DocumentsContract.getDocumentId(uri);
            if (TextUtils.equals(uri.getAuthority(),"com.android.providers.media.documents")){
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if (TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")){
                if (documentId != null && documentId.startsWith("msf:")){
                    resolveMSF(uri,documentId);
                    return;
                }
                Uri contentUri =  ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(documentId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            gameCategoryImg.setImageBitmap(bitmap);
            gameImgStr = ImageUtil.imageToBase64(bitmap);
        }
    }
    private String getImagePath(Uri uri,String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void resolveMSF(Uri uri, String documentId) {
        File file = new File(getCacheDir(),"temp_file" + getContentResolver().getType(uri).split("/")[1]);
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[4*1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,read);
            }
            outputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            gameCategoryImg.setImageBitmap(bitmap);
            gameImgStr = ImageUtil.imageToBase64(bitmap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                getFromAlbum();
            }else{
                myToast.showToastWithImg("访问相册权限被拒绝~",getDrawable(R.drawable.toast_img));
            }
        }

    }
}